﻿using ProjBackEnd.Areas.Crm.Models;
using ProjBackEnd.DBInstance;
using ProjBackEnd.Lib;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Reflection;
using System.Web;

namespace ProjBackEnd.DAL
{
    public class crmLogic
    {
        public static RespCusCoreInfo GetCusCore( int _iPageSize, int _iCurrPage,string _strComcd, string _strCuskey)
        {
            RespCusCoreInfo respReturn = new RespCusCoreInfo();
            CrmBaseDataContext cbctx = new CrmBaseDataContext(sysLogic.GetConnString(sysLogic.DataBaseName.PROJ));
            try
            {
                if (_iPageSize == 0) throw new Exception("每页显示条数不能为0");
                bool hasNextPage = false;
                int iRecTotal, iPageCount;
                string strCuskey = _strCuskey.ToUpper();
                List<CusCore> lstCusCore = new List<CusCore>();
                if (string.IsNullOrEmpty(_strComcd)) //全局范围客户
                {
                    iRecTotal = cbctx.CRM_CUSTOMERTB.Count(n => n.cuscd.Contains(strCuskey) || n.cusnm.Contains(strCuskey) || n.cusnm_alias.Contains(strCuskey));
                    if ((iRecTotal / _iPageSize - _iCurrPage) > 0) hasNextPage = true;
                    else if ((iRecTotal / _iPageSize - _iCurrPage) == 0) if ((iRecTotal % _iPageSize) > 0) hasNextPage = true;
                    iPageCount = (iRecTotal == 0 ? 0 : iRecTotal / _iPageSize + 1);
                    lstCusCore = cbctx.CRM_CUSTOMERTB.Where(n => n.cuscd.Contains(strCuskey) || n.cusnm.Contains(strCuskey) || n.cusnm_alias.Contains(strCuskey))
                                                                                .OrderBy(n => n.cuscd)
                                                                                .Take(_iPageSize * _iCurrPage).Skip(_iPageSize * (_iCurrPage - 1)).AsEnumerable()
                                                                                .Select(n => new CusCore
                                                                                {
                                                                                    cuscd = n.cuscd,
                                                                                    cusnm = n.cusnm,
                                                                                    cusid = n.cusid,
                                                                                    optlb = GlobalSettings.ENTITYOPERATION_NONE
                                                                                }).ToList();
                }
                else //仅本公司客户
                {
                    iRecTotal = cbctx.VIEW_CRM_COMCUSINFO.Count(n => n.comcd == _strComcd && (n.cuscd.Contains(strCuskey) || n.cusnm.Contains(strCuskey) || n.cusnm_alias.Contains(strCuskey)));
                    if ((iRecTotal / _iPageSize - _iCurrPage) > 0) hasNextPage = true;
                    else if ((iRecTotal / _iPageSize - _iCurrPage) == 0) if ((iRecTotal % _iPageSize) > 0) hasNextPage = true;
                    iPageCount = (iRecTotal == 0 ? 0 : iRecTotal / _iPageSize + 1);
                    lstCusCore = cbctx.VIEW_CRM_COMCUSINFO.Where(n => n.comcd == _strComcd
                                                                                                     && (n.cuscd.Contains(strCuskey) || n.cusnm.Contains(strCuskey) || n.cusnm_alias.Contains(strCuskey)))
                                                                                            .OrderBy(n => n.cuscd)
                                                                                            .Take(_iPageSize * _iCurrPage).Skip(_iPageSize * (_iCurrPage - 1)).AsEnumerable()
                                                                                            .Select(n => new CusCore
                                                                                            {
                                                                                                cuscd = n.cuscd,
                                                                                                cusnm = n.cusnm,
                                                                                                cusid = n.cusid,
                                                                                                optlb = GlobalSettings.ENTITYOPERATION_NONE
                                                                                            }).ToList();
                }

                respReturn.result = new ResultCusName { cuscorelist = lstCusCore, hasnextpage = hasNextPage, pagecount = iPageCount, reccount = iRecTotal };
            }
            catch (Exception ex)
            {
                DataUtil.WriteLog(MethodBase.GetCurrentMethod().Name, ex.Message);
                respReturn.statusCode = 90005;
                respReturn.statusMsg = "数据访问异常。" + ex.Message;
            }
            finally { if (cbctx.Connection.State != ConnectionState.Closed) cbctx.Connection.Close(); }
            return respReturn;
        }

        public static RespCusBaseInfo GetCusBaseInfo(int _iPageSize, int _iCurrPage, string _strComcd, int _iTagid,int _iCusid,string _strCusnm,string _strCusAlias)
        {
            RespCusBaseInfo respReturn = new RespCusBaseInfo();
            CrmBaseDataContext cbctx = new CrmBaseDataContext(sysLogic.GetConnString(sysLogic.DataBaseName.PROJ));
            try
            {
                if (_iPageSize == 0) throw new Exception("每页显示条数不能为0");
                bool hasNextPage = false;
                int iRecTotal=0, iPageCount=0;
                List<CusBaseInfo> lstCusBaseInfo = new List<CusBaseInfo>();
                #region 不按分类筛选
                if (_iTagid == 0)
                {
                    iRecTotal = cbctx.VIEW_CRM_COMCUSINFO.Count(n => (_iCusid == 0 ? true : n.cusid == _iCusid)
                                                                                                            && n.comcd == _strComcd 
                                                                                                            && n.freezelb == "N" 
                                                                                                            && (string.IsNullOrEmpty(_strCusAlias) ? true : n.cusnm_alias.ToUpper().StartsWith(_strCusAlias.ToUpper()))
                                                                                                            && (string.IsNullOrEmpty(_strCusnm) ? true : n.cusnm.Contains(_strCusnm)));
                    if ((iRecTotal / _iPageSize - _iCurrPage) > 0) hasNextPage = true;
                    else if ((iRecTotal / _iPageSize - _iCurrPage) == 0) if ((iRecTotal % _iPageSize) > 0) hasNextPage = true;
                    iPageCount = (iRecTotal == 0 ? 0 : iRecTotal / _iPageSize + 1);
                    lstCusBaseInfo = cbctx.VIEW_CRM_COMCUSINFO.Where(n => (_iCusid == 0 ? true : n.cusid == _iCusid)
                                                                                                                && n.comcd == _strComcd
                                                                                                                && n.freezelb == "N"
                                                                                                                && (string.IsNullOrEmpty(_strCusAlias) ? true : n.cusnm_alias.ToUpper().StartsWith(_strCusAlias.ToUpper()))
                                                                                                                && (string.IsNullOrEmpty(_strCusnm) ? true : n.cusnm.Contains(_strCusnm)))
                                                                                                .OrderBy(n => n.cuscd)
                                                                                                .Take(_iPageSize * _iCurrPage).Skip(_iPageSize * (_iCurrPage - 1)).AsEnumerable()
                                                                                                .Select(n => new CusBaseInfo
                                                                                                {
                                                                                                    addrchn = n.addrchn,
                                                                                                    cnybanknm_chn = n.cnybanknm_chn,
                                                                                                    cnybankno = n.cnybankno,
                                                                                                    contact = n.contact,
                                                                                                    comcd = n.comcd,
                                                                                                    corp = n.corp,
                                                                                                    ctcount = n.ctcount,
                                                                                                    cuscd = n.cuscd,
                                                                                                    cuscomref = n.cuscomref,
                                                                                                    cusnm = n.cusnm,
                                                                                                    cusnm_alias = n.cusnm_alias,
                                                                                                    cusnm_sht = n.cusnm_sht,
                                                                                                    cusid = n.cusid,
                                                                                                    deftaxrate = n.deftaxrate,
                                                                                                    optlb = GlobalSettings.ENTITYOPERATION_NONE,
                                                                                                    period = n.period,
                                                                                                    regaddchn = n.regaddrchn,
                                                                                                    taxno = n.taxno,
                                                                                                    taxpayertp = n.taxpayertp,
                                                                                                    tel = n.tel,
                                                                                                    usccode = n.usccode,
                                                                                                    usdbanknm_chn = n.usdbanknm_chn,
                                                                                                    usdbankno = n.usdbankno
                                                                                                }).ToList();
                }
                #endregion
                #region 按分类筛选（暂不考虑客户分类，后续如有需要再补充此逻辑 qm180720）
                else { }
                #endregion
                respReturn.result = new ResultCusBaseInfo { cusbaselist = lstCusBaseInfo, hasnextpage = hasNextPage, pagecount = iPageCount, reccount = iRecTotal };
                respReturn.statusCode = 0;
                respReturn.statusMsg = "";
            }
            catch (Exception ex)
            {
                DataUtil.WriteLog(MethodBase.GetCurrentMethod().Name, ex.Message);
                respReturn.statusCode = 90005;
                respReturn.statusMsg = "数据访问异常。" + ex.Message;
            }
            finally { if (cbctx.Connection.State != ConnectionState.Closed) cbctx.Connection.Close(); }
            return respReturn;
        }

        public static RespCusDetailInfo GetCusDetailInfo(string _strComcd, int _iCusid)
        {
            RespCusDetailInfo respReturn = new RespCusDetailInfo();
            CrmBaseDataContext cbctx = new CrmBaseDataContext(sysLogic.GetConnString(sysLogic.DataBaseName.PROJ));
            try
            {
                VIEW_CRM_COMCUSINFO entity = cbctx.VIEW_CRM_COMCUSINFO.SingleOrDefault(n => n.cusid == _iCusid&&n.comcd==_strComcd);
                if (entity == default(VIEW_CRM_COMCUSINFO)) throw new Exception("未找到客户信息；" + _iCusid.ToString());
                CusDetailInfo collec = new CusDetailInfo();
                collec.addrchn = entity.addrchn;
                collec.addreng = entity.addreng;
                collec.cnybankaddr_chn = entity.cnybankaddr_chn;
                collec.cnybankaddr_eng = entity.cnybankaddr_eng;
                collec.cnybanknm_chn = entity.cnybanknm_chn;
                collec.cnybanknm_eng = entity.cnybanknm_eng;
                collec.cnybankno = entity.cnybankno;
                collec.cnycode = entity.cnycode;
                collec.comcd = _strComcd;
                collec.contact = entity.contact;
                collec.corp = entity.corp;
                collec.cuscd = entity.cuscd;
                collec.cuscomref = "";
                collec.cusnm = entity.cusnm;
                collec.cusnm_alias = entity.cusnm_alias;
                collec.cusnm_sht = entity.cusnm_sht;
                collec.cusid = entity.cusid;
                collec.cusref_inner = entity.cusref_inner;
                collec.deftaxrate = entity.deftaxrate;
                collec.email = entity.email;
                collec.fax = entity.fax;
                collec.freezelb = entity.freezelb;
                collec.mblsfile = entity.mblsfile;
                collec.moddt = (entity.moddt == null ? "" : ((DateTime)entity.moddt).ToString("yyyy-MM-dd HH:mm"));
                collec.modid = entity.modid;
                collec.optlb = GlobalSettings.ENTITYOPERATION_NONE;
                collec.period = entity.period;
                collec.regaddchn = entity.regaddrchn;
                collec.regaddreng = entity.regaddreng;
                collec.taxno = entity.taxno;
                collec.taxpayertp = entity.taxpayertp;
                collec.tel = entity.tel;
                collec.txfile = entity.txfile;
                collec.usccode = entity.usccode;
                collec.usdbankaddr_chn = entity.usdbankaddr_chn;
                collec.usdbankaddr_eng = entity.usdbankaddr_eng;
                collec.usdbanknm_chn = entity.usdbanknm_chn;
                collec.usdbanknm_eng = entity.usdbanknm_eng;
                collec.usdbankno = entity.usdbankno;
                collec.usdcode = entity.usdcode;

                respReturn.result = new ResultCusDetailInfo { cusdetail = collec };
            }
            catch (Exception ex)
            {
                DataUtil.WriteLog(MethodBase.GetCurrentMethod().Name, ex.Message);
                respReturn.statusCode = 90005;
                respReturn.statusMsg = "数据访问异常。" + ex.Message;
            }
            finally { if (cbctx.Connection.State != ConnectionState.Closed) cbctx.Connection.Close(); }
            return respReturn;
        }

        public static RespCusNullResultInfo UpdateCusDetail(string _strMemberid, string _strComcd, CusDetailInfo _collec)
        {
            RespCusNullResultInfo respReturn = new RespCusNullResultInfo();
            CrmBaseDataContext cbctx = new CrmBaseDataContext(sysLogic.GetConnString(sysLogic.DataBaseName.PROJ));
            try
            {
                
                switch (_collec.optlb)
                {
                    #region 增加
                    case "I":
                        CRM_CUSTOMERTB entityBase = cbctx.CRM_CUSTOMERTB.SingleOrDefault(n => n.cusnm == _collec.cusnm);
                        if (entityBase == default(CRM_CUSTOMERTB))
                        {
                            int iCusidNew = sysLogic.GetRefNo("CUS"); //客户基本信息是全局要素，因此流水号不体现公司代码
                            string strCuscomrefNew = sysLogic.GetRefNo(_strComcd, "CUSCOM");
                            if (iCusidNew == 0 || string.IsNullOrEmpty(strCuscomrefNew)) throw new BizException("获取流水号失败");
                            CRM_CUSTOMERTB entityIns = new CRM_CUSTOMERTB
                            {
                                addrchn = _collec.addrchn ?? "",
                                addreng = _collec.addreng ?? "",
                                auditid = "",
                                cnybankaddr_chn = _collec.cnybankaddr_chn ?? "",
                                cnybankaddr_eng = _collec.cnybankaddr_eng ?? "",
                                cnybanknm_chn = _collec.cnybanknm_chn ?? "",
                                cnybanknm_eng = _collec.cnybanknm_eng ?? "",
                                cnybankno = _collec.cnybankno ?? "",
                                cnycode = _collec.cnycode ?? "",
                                contact = _collec.contact ?? "",
                                corp = _collec.corp ?? "",
                                createdt = DateTime.Now,
                                createid = _strMemberid,
                                cuscd = _collec.cuscd ?? "",
                                cusnm = _collec.cusnm ?? "",
                                cusnm_alias = _collec.cusnm_alias ?? "",
                                cusnm_sht = _collec.cusnm_sht ?? "",
                                cusid = iCusidNew,
                                cusref_inner = "",
                                deftaxrate = _collec.deftaxrate,
                                email = _collec.email ?? "",
                                fax = _collec.fax ?? "",
                                tel = _collec.tel ?? "",
                                txfile = "N",
                                freezelb = "N",
                                mblsfile = "N",
                                modid = "",
                                regaddrchn = _collec.regaddchn ?? "",
                                regaddreng = _collec.regaddreng ?? "",
                                taxno = _collec.taxno ?? "",
                                taxpayertp = _collec.taxpayertp ?? "",
                                usccode = _collec.usccode ?? "",
                                usdbankaddr_chn = _collec.usdbankaddr_chn ?? "",
                                usdbankaddr_eng = _collec.usdbankaddr_eng ?? "",
                                usdbanknm_chn = _collec.usdbanknm_chn ?? "",
                                usdbanknm_eng = _collec.usdbanknm_eng ?? "",
                                usdbankno = _collec.usdbankno ?? "",
                                usdcode = _collec.usdcode ?? ""
                            };
                            CRM_CUSTOMER_COM entityIns_com = new CRM_CUSTOMER_COM
                            {
                                auditdt = DateTime.Now,
                                auditid = _strMemberid,
                                createid = _strMemberid,
                                createdt = DateTime.Now,
                                comcd = _strComcd,
                                cuscomref = strCuscomrefNew,
                                cusid = iCusidNew,
                                freezelb = "N",
                                period = _collec.period
                            };
                            cbctx.CRM_CUSTOMER_COM.InsertOnSubmit(entityIns_com);
                            cbctx.CRM_CUSTOMERTB.InsertOnSubmit(entityIns);
                        }
                        else
                        {
                            if (entityBase.freezelb != "N") throw new Exception("客户已被冻结"); //全局冻结则不可重新启用
                            //if (bfctx.VIEW_CRM_COMCUSINFO.Count(n => n.cusnm == _collec.cusnm && n.comcd == _strComcd) > 0) throw new Exception("客户信息已存在");
                            CRM_CUSTOMER_COM entityExist_com = cbctx.CRM_CUSTOMER_COM.SingleOrDefault(n => n.cusid == entityBase.cusid && n.comcd == _strComcd);
                            if (entityExist_com == default(CRM_CUSTOMER_COM))
                            {
                                string strCuscomrefNew = sysLogic.GetRefNo(_strComcd, "CUSCOM");
                                if (string.IsNullOrEmpty(strCuscomrefNew)) throw new BizException("获取流水号失败");
                                CRM_CUSTOMER_COM entityIns_com = new CRM_CUSTOMER_COM
                                {
                                    auditdt = DateTime.Now,
                                    auditid = _strMemberid,
                                    createid = _strMemberid,
                                    createdt = DateTime.Now,
                                    comcd = _strComcd,
                                    cuscomref = strCuscomrefNew,
                                    cusid = entityBase.cusid,
                                    freezelb = "N",
                                    period = _collec.period
                                };
                                cbctx.CRM_CUSTOMER_COM.InsertOnSubmit(entityIns_com);
                            }
                            else
                            {
                                if (entityExist_com.freezelb == "N") throw new BizException("客户信息已存在");
                                entityExist_com.freezelb = "N"; //本公司冻结允许重新启用
                            }
                        }
                        break;
                    #endregion
                    #region 更新
                    case "U":
                        CRM_CUSTOMERTB entityBaseUpd = cbctx.CRM_CUSTOMERTB.SingleOrDefault(n => n.cusid == _collec.cusid);
                        if (entityBaseUpd == default(CRM_CUSTOMERTB)) throw new BizException("未找到客户基本信息");
                        CRM_CUSTOMER_COM entityUpd_com = cbctx.CRM_CUSTOMER_COM.SingleOrDefault(n => n.cusid == _collec.cusid && n.comcd == _strComcd);
                        if(entityUpd_com==default(CRM_CUSTOMER_COM)) throw new BizException("未找到公司客户基本信息");
                        entityUpd_com.period = _collec.period == entityUpd_com.period ? entityUpd_com.period : _collec.period;
                        entityBaseUpd.addrchn = _collec.addrchn ?? entityBaseUpd.addrchn;
                        entityBaseUpd.addreng = _collec.addreng ?? entityBaseUpd.addreng;
                        entityBaseUpd.cnybankaddr_chn = _collec.cnybankaddr_chn ?? entityBaseUpd.cnybankaddr_chn;
                        entityBaseUpd.cnybankaddr_eng = _collec.cnybankaddr_eng ?? entityBaseUpd.cnybankaddr_eng;
                        entityBaseUpd.cnybanknm_chn = _collec.cnybanknm_chn ?? entityBaseUpd.cnybanknm_chn;
                        entityBaseUpd.cnybanknm_eng = _collec.cnybanknm_eng ?? entityBaseUpd.cnybanknm_eng;
                        entityBaseUpd.cnybankno = _collec.cnybankno ?? entityBaseUpd.cnybankno;
                        entityBaseUpd.cnycode = _collec.cnycode ?? entityBaseUpd.cnycode;
                        entityBaseUpd.contact = _collec.contact ?? entityBaseUpd.contact;
                        entityBaseUpd.corp = _collec.corp ?? entityBaseUpd.corp;
                        entityBaseUpd.cuscd = _collec.cuscd ?? entityBaseUpd.cuscd;
                        entityBaseUpd.cusnm = _collec.cusnm ?? entityBaseUpd.cusnm;
                        entityBaseUpd.cusnm_alias = _collec.cusnm_alias ?? entityBaseUpd.cusnm_alias;
                        entityBaseUpd.cusnm_sht = _collec.cusnm_sht ?? entityBaseUpd.cusnm_sht;
                        entityBaseUpd.cusref_inner = string.IsNullOrEmpty(_collec.cusnm_sht) ? entityBaseUpd.cusref_inner : _collec.cusref_inner;
                        entityBaseUpd.deftaxrate = _collec.deftaxrate;
                        entityBaseUpd.email = _collec.email ?? entityBaseUpd.email;
                        entityBaseUpd.fax = _collec.fax ?? entityBaseUpd.fax;
                        entityBaseUpd.moddt = DateTime.Now;
                        entityBaseUpd.modid = _strMemberid;
                        entityBaseUpd.regaddrchn = _collec.regaddchn;
                        entityBaseUpd.regaddreng = _collec.regaddreng;
                        entityBaseUpd.taxno = _collec.taxno ?? entityBaseUpd.taxno;
                        entityBaseUpd.taxpayertp = _collec.taxpayertp ?? entityBaseUpd.taxpayertp;
                        entityBaseUpd.tel = _collec.tel ?? entityBaseUpd.tel;
                        entityBaseUpd.usccode = _collec.usccode ?? entityBaseUpd.usccode;
                        entityBaseUpd.usdbankaddr_chn = _collec.usdbankaddr_chn ?? entityBaseUpd.usdbankaddr_chn;
                        entityBaseUpd.usdbankaddr_eng = _collec.usdbankaddr_eng ?? entityBaseUpd.usdbankaddr_eng;
                        entityBaseUpd.usdbanknm_chn = _collec.usdbanknm_chn ?? entityBaseUpd.usdbanknm_chn;
                        entityBaseUpd.usdbanknm_eng = _collec.usdbanknm_eng ?? entityBaseUpd.usdbanknm_eng;
                        entityBaseUpd.usdbankno = _collec.usdbankno ?? entityBaseUpd.usdbankno;
                        entityBaseUpd.usdcode = _collec.usdcode ?? entityBaseUpd.usdcode;
                        break;
                    #endregion
                    #region 删除
                    case "D":
                        CRM_CUSTOMERTB entityBaseDel = cbctx.CRM_CUSTOMERTB.SingleOrDefault(n => n.cusid == _collec.cusid);
                        if (entityBaseDel == default(CRM_CUSTOMERTB)) throw new BizException("未找到客户基本信息");
                        CRM_CUSTOMER_COM entityDel_com = cbctx.CRM_CUSTOMER_COM.SingleOrDefault(n => n.cuscomref == _collec.cuscomref);
                        if (entityDel_com == default(CRM_CUSTOMER_COM)) throw new BizException("未找到当前公司客户信息");
                        entityDel_com.freezelb = "Y";
                        break;
                    #endregion
                    default: throw new Exception("操作标识符异常");
                }
                cbctx.SubmitChanges();
                respReturn.statusMsg = "操作成功";
            }
            catch (BizException ex)
            {
                DataUtil.WriteLog(MethodBase.GetCurrentMethod().Name, ex.Message);
                respReturn.statusCode = 90021;
                respReturn.statusMsg = ex.Message;
            }
            catch (Exception ex)
            {
                DataUtil.WriteLog(MethodBase.GetCurrentMethod().Name, ex.Message);
                respReturn.statusCode = 90005;
                respReturn.statusMsg = "数据访问异常。" + ex.Message;
            }
            finally { if (cbctx.Connection.State != ConnectionState.Closed) cbctx.Connection.Close(); }
            return respReturn;
        }


        public static RespCusUnSettled GetCusUnSettled(string _strComcd,string _strCreateid)
        {
            RespCusUnSettled respReturn = new RespCusUnSettled();
            CrmBaseDataContext cbctx = new CrmBaseDataContext(sysLogic.GetConnString(sysLogic.DataBaseName.PROJ));
            try
            {
                List<CusCore> lst = cbctx.VIEW_CRM_CUSUNSETTLED.Where(n => n.comcd == _strComcd
                                                                                                                && string.IsNullOrEmpty(_strCreateid) ? true : n.createid == _strCreateid).AsEnumerable()
                                                                                                   .Select(n => new CusCore
                                                                                                   {
                                                                                                       cuscd = n.cuscd,
                                                                                                       cusid = n.cusid,
                                                                                                       cusnm = n.cusnm,
                                                                                                       cusnm_sht = n.cusnm_sht,
                                                                                                       optlb = GlobalSettings.ENTITYOPERATION_NONE
                                                                                                   }).ToList();
                respReturn.result = new ResultCusUnSettled { cuscorelist = lst };
            }
            catch (BizException ex)
            {
                DataUtil.WriteLog(MethodBase.GetCurrentMethod().Name, ex.Message);
                respReturn.statusCode = 90021;
                respReturn.statusMsg = ex.Message;
            }
            catch (Exception ex)
            {
                DataUtil.WriteLog(MethodBase.GetCurrentMethod().Name, ex.Message);
                respReturn.statusCode = 90005;
                respReturn.statusMsg = "数据访问异常。" + ex.Message;
            }
            finally { if (cbctx.Connection.State != ConnectionState.Closed) cbctx.Connection.Close(); }
            return respReturn;
        }

    }
}